// 节流
// 第一次会被调用，最后一次不会再被调用 leading:true,trailing:false
// 第一次不会被调用，最后一次会再被调用 leading:false,trailing:true
// 第一次和最后一次都会被调用 leading:true,trailing:true
export function _throttle(func, wait, options) {
  var timeout, context, args, result
  var previous = 0
  if (!options) options = {}

  const later = function() {
    previous = new Date().valueOf()
    timeout = null
    result = func.apply(context, args)
    if (!timeout) context = args = null
  }
  var throttled = function() {
    context = this
    args = arguments
    const now = new Date().valueOf()
    if (options.leading === false && !previous) previous = now
    var remaining = wait - (now - previous)
    if (remaining <= 0 || remaining > wait) {
      // 第一次会直接执行
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now
      result = func.apply(context, args)
      if (!timeout) context = args = null
    } else if (!timeout && options.trailing !== false) {
      // 最后一次会被执行
      timeout = setTimeout(later, remaining)
    }
    return result
  }

  throttled.cancel = function() {
    clearTimeout(timeout)
    previous = 0
    timeout = context = args = null
  }

  return throttled
}
